package com.core.asyncManager.factory;


import com.common.utils.Constants;
import com.common.emums.Status;
import com.common.exception.BusinessException;
import com.common.utils.*;
import com.core.springSecurity.common.FingerprintUtils;
import com.core.springSecurity.common.SecurityUtils;
import com.core.springSecurity.model.LoginUserDetails;
import com.core.springSecurity.service.TerminalService;
import com.model.pojo.sys.SysLoginInfo;
import com.model.pojo.sys.SysOperLog;
import com.service.sys.SysLoginInfoService;
import com.service.sys.SysOperLogService;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;

import java.util.TimerTask;


 /**
 * @Author: zql
 * @Description: 异步工厂（产生任务用）
 * @Data: 11:35 2021/8/11
 */
@Slf4j
public class AsyncFactory {

   // private static final Logger logger = LoggerFactory.getLogger("AsyncFactory");

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message,
                                             final Object... args) {
        String fingerprintDeviceID = FingerprintUtils.getFingerprintDeviceID();
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = NetworkUtils.getIPAddress(ServletUtils.getRequest());
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIp(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                //s.append(LogUtils.getBlock(UserType.getInfo(sysUser.getUserType())));
                // 打印信息到日志
                //logger.info(s.toString(), args);
                log.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLoginInfo sysLoginInfo = new SysLoginInfo();
//                sysLoginInfo.setSysUserId(sysUser.getSysUserId());
//                sysLoginInfo.setSysDeptId(sysUser.getSysDeptId());
                sysLoginInfo.setUserName(username);
                sysLoginInfo.setIpaddr(ip);
//                sysLoginInfo.setUserType(sysUser.getUserType());
                sysLoginInfo.setLoginLocation(address);
                sysLoginInfo.setBrowser(browser);
                sysLoginInfo.setOs(os);
                sysLoginInfo.setMsg(message);
                // 日志状态
                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
                    sysLoginInfo.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    sysLoginInfo.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(SysLoginInfoService.class).create(sysLoginInfo,username);
            }
        };
    }


    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysOperLog operLog, Exception e) {
        //获取请求信息
        String fingerprintDeviceID = FingerprintUtils.getFingerprintDeviceID();
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = NetworkUtils.getIPAddress(ServletUtils.getRequest());
        String userName = SecurityUtils.getUsername();
        String url = ServletUtils.getRequest().getRequestURI();

        return new TimerTask() {
            @Override
            public void run() {
                //记录执行状态
                if (e != null) {
                    if (e instanceof BusinessException) {
                        BusinessException b = (BusinessException) e;
                        operLog.setErrorMsg(StringUtils.substring(b.getErrorCodeEnum().getErrorMsg(), 0, 2000));
                    } else {
                        operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
                    }
                    operLog.setStatus(Status.DISABLE.getCode());
                }
                //记录访问者ip
                operLog.setOperIp(ip);
                //记录访问的url
                operLog.setOperUrl(url);
                //记录访问者登录名
                operLog.setUserName(userName);
                // 获取客户端操作系统
                operLog.setOs(userAgent.getOperatingSystem().getName());
                // 获取客户端浏览器
                operLog.setBrowser(userAgent.getBrowser().getName());
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIp(operLog.getOperIp()));
                // 入库
                SpringUtils.getBean(SysOperLogService.class).create(operLog);
            }
        };
    }

    public static TimerTask updateTerminal(LoginUserDetails loginUserDetails) {
        return new TimerTask() {
            @Override
            public void run() {
                SpringUtils.getBean(TerminalService.class).updateUser(loginUserDetails);
            }
        };
    }

}